package com.aube.activity;

import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.BaseActivity;
import com.aube.R;
import com.aube.model.HomeCategoryModel;
import com.aube.push.PushSetting;
import com.aube.tinker.TinkerPatchManager;
import com.aube.utils.UpgradeUtil;
import com.aube.views.RealtimeBlurView;
import com.huyn.baseframework.dynamicload.DLContentView;
import com.huyn.baseframework.dynamicload.OnShareChannelSelected;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.WXLoginModel;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.share.WxUtil;
import com.huyn.baseframework.utils.AppUtil;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * Created by huyaonan on 16/5/16.
 */
public class PluginMainActivity extends BaseActivity {

    private static final float SCALE_INT = 1.2F;
    private static final int SPLASH_TIME = 3000;
    private static final int ERROR_TIME = 20000;
    private float mTranslateY;

    private ImageView mSplash;
    private View mPoweredByAube, mLogo;
    private TextView mPoweredVersion;

    private FrameLayout mOriginBgLayout;
    private FrameLayout mOriginLayout;

    private ViewGroup mRoot;
    private View mPluginLoading;

    private RealtimeBlurView mBlurview;
//    private BlurringView mBlurview;
    private PluginLoader mPluginManager;

    private AtomicBoolean mThemeLoadLock = new AtomicBoolean(false);

    private Timer mTimer;

    private BroadcastReceiver mBrr;

    private DLContentView mContent;

    private boolean mDataInit = false;
    private boolean mFromPush = false;
    private String mPushParams;
    private AtomicBoolean mModuleLoaded = new AtomicBoolean(false);

    @Override
    public View getRootView() {
        return mRoot;
    }

    @Override
    public void onClickToVideo(ChannelDetail channelDetail) {
        reportUmengEvent(UmengUtils.FROM_HOME_TO_VIDEO, appendLabels(channelDetail.videoid, channelDetail.videoTitle));
        super.onClickToVideo(channelDetail);
    }

    @Override
    public void onClickToVideo(ChannelDetail channelDetail, Category category) {
        reportUmengEvent(UmengUtils.FROM_HOME_TO_VIDEO, appendLabels(channelDetail.videoid, channelDetail.videoTitle));
        super.onClickToVideo(channelDetail, category);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.plugin_main);

        mRoot = (ViewGroup) findViewById(R.id.main_root);

        mSplash = (ImageView) findViewById(R.id.splash_img);
        mPoweredByAube = findViewById(R.id.powered_by_aube);
        mLogo = findViewById(R.id.aube_logo);
        mPluginLoading = findViewById(R.id.plugin_loading);
        mPoweredVersion = (TextView) findViewById(R.id.powered_version);

        mOriginBgLayout = (FrameLayout) findViewById(R.id.origin_bg_layout);
        mOriginLayout = (FrameLayout) findViewById(R.id.origin_layout);

//        mPoweredVersion.setText("v" + Constant.APP_VERSION);
        mPoweredVersion.setText("v" + Constant.APP_TRUE_VERSION);
        //test tinker
//        mPoweredVersion.setText("v_____" + Constant.APP_VERSION);
//        TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
//        Tinker tinker = Tinker.with(getApplicationContext());
//        if (tinker.isTinkerLoaded()) {
//            //if has new package, remove old patch and add new one
//        }
        TinkerPatchManager.getInstance(this).getPatch();

        mTranslateY = SysUtil.getScreenHeight(this)*0.1f;

        mSplash.setScaleY(SCALE_INT);
        mSplash.setScaleX(SCALE_INT);
        mSplash.setTranslationY(mTranslateY);

        mOriginBgLayout.setScaleY(SCALE_INT);
        mOriginBgLayout.setScaleX(SCALE_INT);
        mOriginBgLayout.setTranslationY(mTranslateY);

        mBlurview = (RealtimeBlurView) findViewById(R.id.blurring_view);
//        mBlurview = (BlurringView) findViewById(R.id.blurring_view);
//        mBlurview.setBlurredView(mOriginBgLayout);

        if(Constant.DEBUG) {
            findViewById(R.id.proxy_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(PluginMainActivity.this, PreferenceActivity.class));
                }
            });
        }

        mBrr = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(UpgradeUtil.APP_CLOSE.equalsIgnoreCase(intent.getAction())) {
                    onExit();
                } else if (Constant.AUTH_SUCCESS_FROM_WX.equalsIgnoreCase(intent.getAction())) {
                    String code = intent.getStringExtra(Constant.AUTH_CODE);

                    // doAuthRequest
                    WxUtil.doWechatLogin(PluginMainActivity.this, code, new Response.Listener<WXLoginModel>() {

                        @Override
                        public void onResponse(WXLoginModel response) {
                            if(response != null && response.success()) {
                                UserUtil.saveInstance(PluginMainActivity.this, response.data);
                                sendBroadcast(new Intent(UserUtil.LOGIN_SUCCESS));
                            }
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {
                        }

                        @Override
                        public void onStart() {
                        }
                    });
                } else if(Constant.MEMBERENCODE_ILLEGAL.equalsIgnoreCase(intent.getAction())) {
                    UserUtil.logout(PluginMainActivity.this);
                    Utils.showToast(PluginMainActivity.this, "您的登陆信息已失效,请重新登陆");
                    if(mContent != null)
                        mContent.update(intent.getAction());
                } else if(PushSetting.PUSH_REGIST_SUCCESS.equalsIgnoreCase(intent.getAction())) {
                    if(mContent != null)
                        mContent.update(intent.getAction());
                } else if(UserUtil.LOGOUT.equalsIgnoreCase(intent.getAction())) {
                    if(mContent != null)
                        mContent.update(intent.getAction());
                } else if(UserUtil.LOGIN_SUCCESS.equalsIgnoreCase(intent.getAction())) {
                    Utils.Log(TAG, "[Broadcast onReceive] LOGIN_SUCCESS");
                    if(mContent != null)
                        mContent.update(intent.getAction());
                    Toast.makeText(context, "登陆成功",Toast.LENGTH_SHORT).show();
                }
            }
        };
        IntentFilter iff = new IntentFilter();
        iff.addAction(UpgradeUtil.APP_CLOSE);
        iff.addAction(Constant.AUTH_SUCCESS_FROM_WX);
        iff.addAction(Constant.MEMBERENCODE_ILLEGAL);
        iff.addAction(PushSetting.PUSH_REGIST_SUCCESS);
        iff.addAction(UserUtil.LOGOUT);
        iff.addAction(UserUtil.LOGIN_SUCCESS);
        registerReceiver(mBrr, iff);

        mPluginManager = PluginLoader.getmInstance(this);

        reportUmengEvent(UmengUtils.OPEN_APP, "");

        mPushParams = getIntent().getStringExtra(PushSetting.PUSH_PARAM);

        if(isValidPush()) {
            //来自push
            mFromPush = true;
        } else {
            //version verify
            new UpgradeUtil().upGrade(this, false);

            mDataInit = true;
        }

        fadeIn();
    }

    @Override
    public void onResume() {
        super.onResume();

        Utils.releaseScreenLock(this);

        if(mContent != null)
            mContent.onResume();

        if(!mDataInit && !mFromPush) {
            mDataInit = true;

            //version verify
            new UpgradeUtil().upGrade(this, false);

            springOut();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mPushParams = intent.getStringExtra(PushSetting.PUSH_PARAM);
        if(StringUtils.isNotBlank(mPushParams)) {
            try {
                Utils.sysout("PUSH_PARAM:" + URLDecoder.decode(mPushParams, "utf-8"));
                doPushJump();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onReady() {
        synchronized (mThemeLoadLock) {
            if(mThemeLoadLock.get()) {
                springOut();
            } else {
                mThemeLoadLock.set(true);
            }
        }
    }

    /**
     * 是可以被解析的push
     * @return
     */
    private boolean isValidPush() {
        if(StringUtils.isNotBlank(mPushParams)) {
            try {
                mPushParams = URLDecoder.decode(mPushParams, "utf-8");
                JSONObject jsonObject = new JSONObject(mPushParams);
                String actionType = jsonObject.optString("type");
                if(StringUtils.isNotBlank(actionType))
                    return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * PUSH跳转处理
     * @return
     */
    private void doPushJump() {
        try {
            mPushParams = URLDecoder.decode(mPushParams, "utf-8");
            if(mContent != null)
                mContent.executePushEvent(mPushParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fadeIn() {
        mPluginManager.getSplashScreen(this, null);
        startModules();
        splashCountDown();
    }

    private void startModules() {
        mPluginManager.getHomeModules(new PluginLoader.IModuleStateListener() {

            @Override
            public void deliverResponse(HomeCategoryModel response) {
                setupModules();
            }
        });
    }

    private void setupModules() {
        if(mPluginManager == null)
            return;

        try {
            mContent = mPluginManager.inflateContentPluginLayout(this, "home", "com.aube.plugin.origin.OriginLauncher");
            mOriginLayout.addView(mContent, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mContent.setDLBridge(this);
            mContent.attachViews(mBlurview, mSplash, mOriginBgLayout);
            mContent.initData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void splashCountDown() {
        if(mTimer == null)
            mTimer = new Timer();
        TimerTask mTask = new TimerTask() {
            @Override
            public void run() {
                synchronized (mThemeLoadLock) {
                    if(mThemeLoadLock.get()) {
                        runOnUiThread(new Runnable() {
                                          @Override
                                          public void run() {
                                              springOut();
                                          }
                                      }
                        );
                    } else {
                        mThemeLoadLock.set(true);
                        //show loading
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWaitingProgress();
                            }
                        });
                    }
                }
            }
        };
        mTimer.schedule(mTask, SPLASH_TIME);

        TimerTask errorTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                                  @Override
                                  public void run() {
                                      showNetworkError();
                                  }
                              }
                );
            }
        };
        mTimer.schedule(errorTask, ERROR_TIME);
    }

    private void showWaitingProgress() {
        if(mModuleLoaded.get())
            return;
        mPluginLoading.setVisibility(View.VISIBLE);
    }

    private void hideWaitingProgress() {
        mModuleLoaded.set(true);
        if(mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mPluginLoading.setVisibility(View.GONE);
    }

    private void showNetworkError() {
        Utils.showToast(this, "启动失败,请重新打开!");
    }

    private void springOut() {
        hideWaitingProgress();

        if(mFromPush) {
            //jump
            doPushJump();
            mFromPush = false;
            return;
        }

        ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
        anim.setDuration(1000);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = (float) animation.getAnimatedValue();
                mLogo.setAlpha(fraction);
                mPoweredByAube.setAlpha(fraction);
            }
        });
        anim.start();
        if(mContent != null)
            mContent.onReady();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(dismissShareLayout())
                return true;
            if(dismissLoginHelper())
                return true;
            if(keyCodeBackPressed(keyCode, event))
                return true;

            if(mContent != null && mContent.onBackPressed())
                return true;

            if(mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            onExit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mContent != null)
            mContent.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBrr != null)
            unregisterReceiver(mBrr);
        if(mContent != null)
            mContent.onDestroy();
    }

    public void onExit() {
        onDestroy();
        AppUtil.exitApp(this, false);
//        //clear resources and movetasktoback
//        moveTaskToBack(true);//退到后台
    }

    @Override
    protected boolean enableSwipeAction() {
        return false;
    }

    @Override
    public void showShareLayout(final OnShareChannelSelected selector) {
        if (mShareLayout == null) {
            generatorShareLayout();
            mRoot.addView(mShareLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        manageShareLayout(true);

        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
            }
        });

        mShareWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
                if(selector != null)
                    selector.onSelected(ShareType.WEIBO);
            }
        });

        mShareWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
                if(selector != null)
                    selector.onSelected(ShareType.WECHAT);
            }
        });

        mShareTimeline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
                if(selector != null)
                    selector.onSelected(ShareType.TIMELINE);
            }
        });
    }
}
